#include "options.h"
#include <getopt.h>
#include <stdexcept>

namespace PESI {

// see http://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Option-Example.html#Getopt-Long-Option-Example
static struct option long_options[] =
{
  {"verbose",    no_argument,       0, 'v'},
  {"help",       no_argument,       0, 'h'},
  {"daemonize",  no_argument,       0, 'd'}, // TODO
  {"log",        required_argument, 0, 'l'}, // TODO
  {"config",     required_argument, 0, 'c'},
  {"pid",        required_argument, 0, 'P'}, // TODO
  {"port",       required_argument, 0, 'p'},
  {"address",    required_argument, 0, 'a'},
  {0, 0, 0, 0}
};

bool Options::parse( int argc, char **argv )
{
  int c, opt_index;
  bool valid = true;

  while( valid ){
    opt_index = 0;

    c = getopt_long( argc, argv, "vhdl:P:p:a:c:", long_options, &opt_index );
    if( c == -1 ){ break; }
    switch( c ){
    case 'v':
      _verbose = true;
      break;
    case 'h':
      _help = true;
      break;
    case 'd':
      _daemonize = true;
      break;
    case 'c':
      _options["config"] = optarg;
      break;
    case 'l':
      _options["log"] = optarg;
      break;
    case 'P':
      _options["pid"] = optarg;
      break;
    case 'p':
      _options["port"] = optarg;
      break;
    case 'a':
      _options["address"] = optarg;
      break;
    default:
      valid = false;
      break;
    }
  }

  return valid;
}

void Options::usage( char **argv )const
{
  printf( "Usage:\n\t%s -p port -b bind\n", argv[0] );
  for( int i = 0, len = sizeof(long_options)/16 -1; i < len; ++i ){
    printf( "--%s\n", long_options[i] );
  }
}

void Options::dump()const
{
  printf( "help: %s, verbose: %s, daemonize: %s\n", 
          (_help ? "yes" : "no"),
          (_verbose ? "yes" : "no"),
          (_daemonize ? "yes" : "no") );
  for( OptTable::const_iterator i = _options.begin(); i != _options.end(); ++i ){
    printf( "%s : %s\n", i->first, i->second.c_str() );
  }
}

}
